package com.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.entity.CorrectJsonObject;
import com.demo.entity.ErrorJsonObject;
import com.demo.entity.News;
import com.demo.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/news")
public class NewsController {

    @Autowired
    NewsService newsService;

    @ResponseBody//返回json数据
    @RequestMapping(value = "/getNews",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    public String getNews(@RequestParam(value = "id",required = false) Integer id,Model model) {
        if(id == null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101,"id为空");
            return JSONObject.toJSONString(errorJsonObject);
        }

        News news = new News();
        news = newsService.findNewsById(id);

        if(news == null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101,"查询失败");
            return JSONObject.toJSONString(errorJsonObject);
        }else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(news);
            return JSONObject.toJSONString(correctJsonObject);
        }
    }

    @RequestMapping(value = "/userLogin",method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    public String userLogin(HttpServletRequest request) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(username.equals("123") && password.equals("123")) {
            return "success";
        }else {
            request.setAttribute("result","账号或密码错误");
            return "index";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getall",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    public String getALL(){

        List<News> list = new ArrayList<>();
        list = newsService.findAll();

        if(list.isEmpty()) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102,"查询失败");
            return JSONObject.toJSONString(errorJsonObject);
        }else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.setData(list);
            return JSONObject.toJSONString(correctJsonObject);
        }
    }
}
